<template>
  <div class="login">
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <!-- 普通登录页面的结构 -->
      <div
        class="commonlogin"
        v-if="iserweima == 'icon-erweima' && issmslogin == false"
      >
        <h1>管理系统</h1>
        <el-form-item label="用户名" prop="username" class="username">
          <el-input
            type="text"
            v-model="ruleForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label=" 密码" prop="password" class="password">
          <el-input
            type="password"
            v-model="ruleForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="chptcha" class="chptcha">
          <el-input
            v-model="ruleForm.chptcha"
            maxlength="5"
            @keydown.native.enter="submitForm('ruleForm')"
          ></el-input>
          <span v-loading="loading">
            <i @click="newchptcha" v-html="img"></i>
          </span>
        </el-form-item>
        <el-form-item class="submitbtn">
          <el-button type="primary" @click="submitForm('ruleForm')">
            提交
          </el-button>
        </el-form-item>

        <div class="tophone">
          <span class="iconfont icon-shouji"></span>
          <a href="javascript:;" @click="issmslogin = !issmslogin">
            手机验证码登录
          </a>
        </div>
      </div>

      <!-- 二维码登录页面的结构 -->
      <div
        class="erweimalogin"
        v-else-if="iserweima == 'icon-diannao' && issmslogin == false"
      >
        <div>
          <h1>微信扫码登录</h1>
          <i :style="qrstyle" @click="shuanxinqr" v-show="issaoma"></i>
          <img :src="qrimgurl" />

          <div></div>
        </div>
        <p>{{ erweimatext }}</p>
      </div>
      <!-- 手机短信验证 -->
      <div class="smslogin" v-else-if="issmslogin == true">
        <el-form>
          <el-form-item label="手机号" prop="smsphone" class="smsphone">
            <el-input
              type="text"
              autocomplete="off"
              v-model="smschptchaphone"
            ></el-input>
            <span>
              <i @click="sendsmsphne">{{ smsdaojishi }}</i>
            </span>
          </el-form-item>
          <el-form-item label="验证码" prop="smschptcha" class="smschptcha">
            <el-input
              type="text"
              v-model="smschptchanumber"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="smsphonechaptcha">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-form>

    <!-- <video id="v1" autoplay loop muted>
      <source src="../../utils/video/bg.mp4" type="video/mp4" />
    </video> -->

    <span @click="changeiserweima" :class="['iconfont', iserweima]"></span>
    <!-- 二维码的图标引入 -->
  </div>
</template>

<script>
var validatechptcha = (rule, value, callback) => {
  //用于判断验证码
  if (!value) {
    callback("验证码不能为空");
  } else {
    callback();
  }
};
var validateusername = (rule, value, callback) => {
  let userchptcha = /^[a-zA-Z0-9_-]{3,20}$/;
  //用于判断用户名
  if (!userchptcha.test(value)) {
    callback("用户名正则，4到16位（字母，数字，下划线，减号）");
  } else {
    callback();
  }
};
//用于判断密码
var validatepassword = (rule, value, callback) => {
  if (value === "") {
    callback("请输入密码");
  } else {
    callback();
  }
};
//调用方法
import {
  getChptcha,
  verifyCaptcha,
  login,
  getQrcode,
  wechatLogin,
  getSmscode,
  smslogin,
} from "../../api/users";
//引入二维码的相关成功失败图片
import succ from "../login/over/succ.webp";
import def from "../login/over/def.webp";
//引入sockt
import socketIo from "socket.io-client";
//引入qrcode
import qr from "qrcode";
import { mapMutations } from "vuex";
export default {
  data() {
    return {
      img: null,
      //验证码
      loading: true,
      //验证码转圈圈
      iserweima: "icon-erweima",
      //登录电脑二维码图标
      issmslogin: false,
      //控制手机登录
      issaoma: false,
      //二维码遮罩显示
      qrimgurl: "",
      //二维码图标转图片的地址
      // qrloading: true,
      //二维码load动画
      erweimatext: "请用微信扫码登录",
      //手机短信内容
      smsdaojishi: "点击发送验证码",
      //是否可以点击发送短信
      issondsmsphone: false,
      ruleForm: {
        username: "",
        password: "",
        chptcha: "",
      },

      smschptchaphone: "",
      smschptchanumber: "",

      rules: {
        username: [{ validator: validateusername, trigger: "blur" }],
        password: [{ validator: validatepassword, trigger: "blur" }],
        chptcha: [{ validator: validatechptcha, trigger: "blur" }],
      },
      qrstyle: {
        backgroundImage: `url(${def})`,
      },
    };
  },
  //监听
  watch: {
    iserweima: {
      handler(newdata) {
        if (newdata == "icon-diannao") {
          //监听界面图标二维码图标的转换,因为是https协议 所以是wss
          //动画开始 二维码上面的动画
          // this.qrloading = false;
          let io = socketIo("wss://chst.vip");
          io.on("scancodeSuccess", async (data) => {
            //用户微信扫码返回临时code
            let wechatCode = data.wechatCode;
            if (wechatCode) {
              //如果扫码成功  二维码出现成功的遮罩
              this.issaoma = true;
              this.qrstyle.backgroundImage = `url(${succ})`;
              //如果扫码成功
              let wechatLogindata = await wechatLogin(wechatCode);
              let token = wechatLogindata.data.token;
              let permissionbtn = wechatLogindata.data.permission.buttons;
              let userInfo = wechatLogindata.data.userInfo;

              if (wechatLogindata.data.state) {
                //存储信息
                localStorage.setItem("token", token);
                localStorage.setItem(
                  "permission",
                  JSON.stringify(permissionbtn)
                );
                localStorage.setItem("userInfo", JSON.stringify(userInfo));
                //存储信息
                this.$router.push("/");
                this.issaoma = false;
              }
            }
          });
          io.on("invalidCode", (data) => {
            //无效二维码主体内容
            let defstate = data.state;
            if (!defstate) {
              this.issaoma = true;
              //二维码的失败的遮罩出现
              this.erweimatext = "二维码失效 ，点击刷新";
              //修改二维码下面的文字
            }
          });
          //建立链接
          io.on("connectSuccess", async (sid) => {
            // console.log(sid);
            localStorage.setItem("sid", sid.sid);

            let Qrcode = await getQrcode(sid.sid);
            //请求获得二维码的Qrcode
            if (Qrcode.data) {
              //如果获取到数据
              let url = Qrcode.data.scanCodeUrl;
              //进一步提取二维码的 url
              qr.toDataURL(url, (err, baseimg64) => {
                if (err) {
                  //如果有错误抛出错误
                  this.$messageBox.error(err);
                  return;
                } else {
                  //如果正确将地址给data里面的数据展示 图片
                  this.qrimgurl = baseimg64;
                  //动画消失 二维码上面的动画
                  // this.qrloading = false;
                }
              });
            }
          });
          //建立链接处理
        }
      },
    },
  },
  methods: {
    ...mapMutations(["SET_USERINFO"]),
    //二维码遮罩点击事件
    async shuanxinqr() {
      this.erweimatext = "请用微信扫码登录";
      //修改二维码下面的文字
      this.issaoma = false;
      let sid = localStorage.getItem("sid");
      let Qrcode = await getQrcode(sid);
      //请求获得二维码的Qrcode
      if (Qrcode.data) {
        //如果获取到数据
        let url = Qrcode.data.scanCodeUrl;
        //进一步提取二维码的 url
        qr.toDataURL(url, (err, baseimg64) => {
          if (err) {
            //如果有错误抛出错误
            this.$messageBox.error(err);
            return;
          } else {
            //如果正确将地址给data里面的数据展示 图片
            this.qrimgurl = baseimg64;
            //动画消失 二维码上面的动画
            // this.qrloading = false;
          }
        });
      }
    },
    //电脑二维码点击事件
    changeiserweima() {
      if (this.iserweima == "icon-erweima") {
        this.iserweima = "icon-diannao";
      } else if (this.iserweima == "icon-diannao") {
        this.iserweima = "icon-erweima";
      }

      this.issmslogin = false;
    },
    submitForm(formName) {
      // console.log(this.$refs);
      this.$refs[formName].validate((valid) => {
        //只要开始加载就有遮罩动画
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "正在登录中......",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });

          let { username, password, chptcha } = this.ruleForm;
          //提交登录成功
          verifyCaptcha(chptcha).then((res) => {
            //验证码校验登录
            let { state } = res.data;
            if (state) {
              //验证码校验成功
              login(username, password).then((res) => {
                //验证码用户名密码
                // console.log(res);
                let loginstate = res.data.state;
                let loginmsg = res.data.msg;
                let token = res.data.token;
                let userInfo = res.data.userInfo;
                let permissionbtn = res.data.permission.buttons;
                // console.log(logintoken);

                if (loginstate) {
                  //用户名密码登录成功
                  //关闭遮罩
                  loading.close();

                  //出现登录成功的小弹窗
                  this.$message({
                    message: loginmsg,
                    type: "success",
                    duration: 1000,
                  });

                  // 将logintoken存在local里面
                  localStorage.setItem("token", token);
                  localStorage.setItem(
                    "permission",
                    JSON.stringify(permissionbtn)
                  );

                  localStorage.setItem("userInfo", JSON.stringify(userInfo));
                  this.SET_USERINFO(userInfo);

                  //跳转到主页
                  this.$router.push("/");
                } else {
                  //关闭遮罩
                  loading.close();
                  //用户名密码登录失败
                  // this.$confirm("失败",{type="error"});
                }
              });
            } else {
              //验证码校验失败
              getChptcha().then((res) => {
                this.img = res.data.img;
                this.loading = false;
              });
              //关闭遮罩
              loading.close();
            }
          });
        } else {
          //关闭遮罩
          loading.close();
          //提交登录失败
        }
      });
    },
    newchptcha() {
      this.loading = true;
      //验证码点击的时候也刷新一次验证码
      getChptcha().then((res) => {
        this.img = res.data.img;
        this.loading = false;
      });
    },
    //手机短信校验提交函数
    smsphonechaptcha() {
      let code = this.smschptchanumber;
      smslogin(code).then((res) => {
        console.log(res);
        if (res.data.status) {
          let permissionbtn = res.data.permission.buttons;
          let token = res.data.token;
          let userInfo = res.data.userInfo;
          localStorage.setItem("token", token);
          localStorage.setItem("permission", JSON.stringify(permissionbtn));
          localStorage.setItem("userInfo", JSON.stringify(userInfo));
          //存储信息
          this.$router.push("/");
        }
      });
    },
    //手机短信发送函数
    sendsmsphne() {
      if (this.issondsmsphone) {
        this.$message.error("一分钟只能发送一次");
        return;
      }
      let phoneNumber = this.smschptchaphone;
      getSmscode(phoneNumber).then((res) => {
        if (res.data.state) {
          this.$message.success("短信发送成功");
          this.issondsmsphon = true;
          let t;
          clearTimeout(t);
          let num = 10;
          console.log(num);
          t = setInterval(() => {
            num--;
            this.smsdaojishi = `倒计时${num}秒`;
            if (num == 0) {
              clearTimeout(t);
              this.smsdaojishi = "点击发送验证码";
              return;
            }
          }, 1000);
          this.issondsmsphon = false;
          num = 10;
        }

        console.log(res);
      });
    },
  },
  mounted() {
    this.loading = true;
    //加载页面的时候调用一次验证码
    getChptcha().then((res) => {
      this.img = res.data.img;
      this.loading = false;
    });
  },
};
</script>

<style lang="less" scoped>
* {
  margin: 0;
  padding: 0;
}
.login {
  position: absolute;
  width: 100%;
  height: 100%;
}

.demo-ruleForm {
  width: 300px;
  height: 400px;
  background-color: rgba(9, 9, 9, 0.3);
  position: absolute;
  top: 200px;
  right: 200px;
  border-radius: 15px;
  z-index: 11;
  /deep/ .el-form-item__label {
    color: rgb(255, 255, 255);
    font-size: 20px;
  }
  /deep/ h1 {
    color: rgb(255, 255, 255);
    text-align: center;
    margin-top: 20px;
    font-size: 30px;
  }
}
//给普通登录添加样式开始
.username {
  margin-top: 30px;
  margin-left: -20px;

  .el-input {
    width: 200px;
  }
}
.password {
  margin-top: 30px;
  margin-left: -20px;
  .el-input {
    width: 200px;
  }
}
.chptcha {
  margin-top: 30px;
  margin-left: -20px;
  .el-input {
    width: 80px;
    margin-bottom: 20px;
    box-sizing: border-box;
  }
  span {
    display: block;
    position: relative;
    width: 120px;
    height: 40px;
    background-color: rgb(255, 255, 255);

    left: 75px;
    top: -60px;

    /deep/ svg {
      position: relative;
      top: -5px;
      left: -15px;
    }
  }
}
//普通登录页面的手机图标
.tophone {
  position: absolute;
  height: 20px;
  width: 120px;
  right: 0px;
  top: 150px;

  /deep/ .icon-shouji {
    color: rgb(55, 202, 228);
  }
  a {
    position: relative;
    top: 210px;
    right: 80px;
    color: rgb(255, 255, 255);
    text-decoration: underline;
  }
  a:hover {
    color: rgb(252, 0, 0);
  }
}
.submitbtn {
  margin-left: 30px;
  margin-top: -40px;
  .el-button {
    background-color: rgb(255, 0, 0);
    width: 80px;
    height: 30px;
  }
}
//给普通登录添加样式结束

video {
  position: fixed;
  right: 0px;
  bottom: 0px;
  min-width: 100%;
  min-height: 100%;
  height: auto;
  width: auto;
  z-index: -11;
}

// 二维码的样式
.iconfont {
  font-size: 50px;
  position: absolute;
  color: rgb(255, 255, 255);
  top: 200px;
  right: 200px;
  font-weight: 900;
  border-radius: 15px;
  z-index: 22;
}
//扫码登录的样式
.erweimalogin {
  img {
    width: 250px;
    height: 250px;
    position: relative;
    left: 30px;
    top: 20px;
  }
  i {
    position: absolute;
    z-index: 66;
    width: 250px;
    height: 250px;
    left: 30px;
    top: 80px;
    background-repeat: no-repeat;
    background-size: 250px 250px;
    opacity: 0.7;
  }
  p {
    color: rgb(255, 255, 255);
    text-align: center;
    margin-top: 50px;
  }
}
//手机登录的样式
.smslogin {
  position: absolute;

  width: 300px;
  right: 200px;
  top: 100px;
  right: -10px;
  .el-button {
    background-color: rgb(255, 0, 0);
    width: 80px;
    height: 30px;
    margin-left: 90px;
    margin-top: 30px;
  }

  .smschptcha {
    // margin-top: 30px;

    margin-left: 5px;

    .el-input {
      width: 210px;
    }
  }
  .smsphone {
    right: 200px;
    margin-left: 5px;
    margin-top: 30px;
    .el-input {
      position: relative;
      width: 120px;
      margin-bottom: 20px;
      box-sizing: border-box;
      background-color: rgb(146, 215, 206);
    }
    span {
      display: block;
      position: relative;
      width: 90px;
      height: 40px;
      background-color: rgb(255, 255, 255);

      left: 190px;
      top: -60px;
      i {
        font-size: 3px;
        text-decoration: underline;
      }
      i:hover {
        color: rgb(252, 0, 0);
      }
    }
  }
}
</style>
